<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>摄像头</title>
        <style>
            .container {
                width: 1200px;
                height: 600px;
                margin: 100px auto 0;
                display: flex;
                box-shadow: 0 0 8px #333;
            }

            .video-wrapper {
                position: relative;
                overflow: hidden;
                width: 800px;
            }

            .video-wrapper::after {
                content: '';
                position: absolute;
                left: 50%;
                top: 50%;
                transform: translate(-50%, -50%);
                width: 225px;
                height: 300px;
                background: transparent;
                border: 2px solid red;
            }

            video {
                position: absolute;
                width: 800px;
                height: 600px;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
            }

            .control {
                flex: 1;
                display: flex;
                flex-direction: column;
                justify-content: space-around;
            }

            .control > canvas {
                width: 225px;
                height: 300px;
                margin: 0 auto;
                display: block;
                outline: 1px solid #999;
            }

            .control > button {
                width: 180px;
                height: 40px;
                margin: 0 auto;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <div class="video-wrapper">
                <video width="800" height="600"></video>
            </div>
            <div class="control">
                <canvas></canvas>
                <button>拍照</button>
            </div>
        </div>
        <script>
            let p = navigator.mediaDevices.getUserMedia({video: true});
            let video = document.querySelector('video');
            let button = document.querySelector('button');
            let canvas = document.querySelector('canvas');
            let context = canvas.getContext('2d');
            p.then((mediaStream) => {
                video.src = window.URL.createObjectURL(mediaStream);
                video.onloadedmetadata = function () {
                    video.play();
                };
            }).catch((err) => {
                console.log(err.name + ": " + err.message);
            });
            button.addEventListener('click', () => {
                context.drawImage(video, 0, 0, 800, 600);
            }, false);
        </script>
    </body>
</html>